//
//  EditAvatarView.swift
//  cysLibrarySys
//
//  Created by 曹亚索 on 2021/6/25.
//

import UIKit

protocol PickAvatarDelegate {
    func sendAvatar(name:String)
}

class EditAvatarView: UICollectionView {

    private var avatar : [String] = []
    var pickAvatar: PickAvatarDelegate?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        commonInit()
    }
    
    func commonInit(){
        self.layer.cornerRadius = self.frame.width / 10
        self.layer.shadowOffset = CGSize(width: 10, height: 10)
        self.layer.shadowColor = UIColor.gray.cgColor
        self.layer.shadowOpacity = 1
        self.backgroundColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
        self.dataSource = self
        self.delegate = self
        for i in 1...10{
            avatar.append("avatar\(i)")
        }
        let nib = UINib(nibName: "EditAvatarCell", bundle: nil)
        self.register(nib, forCellWithReuseIdentifier: String(describing: EditAvatarCell.self))
//        self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissEditAvatarView(tap:))))
    }
    
    @objc func dismissEditAvatarView(tap:UIGestureRecognizer){
        switch tap.state {
        case .ended:
            self.removeFromSuperview()
        default:
            break
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension EditAvatarView: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return avatar.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: EditAvatarCell.self), for: indexPath) as! EditAvatarCell
        let image = UIImage(named: avatar[indexPath.item])
        cell.avatarsImageView.image = image
        cell.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
        cell.layer.cornerRadius = 10
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        pickAvatar?.sendAvatar(name: avatar[indexPath.item])
        LC.userSetAvatar(avatar: avatar[indexPath.row])
        self.removeFromSuperview()
    }
    
}
